package cn.com.dragonsoftbravo.utils.azure.uploadwork;

import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.concurrent.CountDownLatch;

import com.microsoft.azure.storage.blob.CloudBlobDirectory;
import com.microsoft.azure.storage.blob.CloudBlockBlob;

import cn.com.dragonsoftbravo.utils.azure.AzureConstants;
import cn.com.dragonsoftbravo.utils.azure.BlobService;
import cn.com.dragonsoftbravo.utils.azure.factory.BlobContainerFactory;
import cn.com.dragonsoftbravo.utils.azure.utils.MetadataUtils;

public class UploadWorker extends Thread {

	int index;
	InputStream is;
	CloudBlockBlob blob;
	CountDownLatch latch;
	int fileType;
	String campaignId;
	String extName;

	public UploadWorker(int index, InputStream is, CloudBlockBlob blob, CountDownLatch latch, int fileType, String campaignId, String extName) {
		this.index = index;
		this.is = is;
		this.blob = blob;
		this.latch = latch;
		this.fileType = fileType;
		this.campaignId = campaignId;
		this.extName = extName;
	}

	public void run() {

		try {
			String blobName;

			if (index == 0) {
				blobName = BlobService.uploadToContainer(is, blob.getName());
			} else {
				CloudBlobDirectory directory = BlobContainerFactory.getDirectoryName(campaignId, fileType);
				blobName = BlobService.uploadThumbnail(is, directory, extName);
			}

			if (fileType == 0) {

				if (index == 1) {
					MetadataUtils.setMetaData(blob, AzureConstants.THUMBNAIL_IMAGE_BLOB_NAME, blobName);
				} else if (index == 2) {
					MetadataUtils.setMetaData(blob, AzureConstants.THUMBNAIL_IMAGE_BLOB_NAME2, blobName);
				}
			}

			if (latch != null) {
				latch.countDown();
			}
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
